package com.wf.mock.app.mina.dto;

import java.util.Collections;
import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.wf.mock.app.utils.Base64Util;
import com.wf.mock.app.utils.MinaUtils;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class SplitMsgPacketDTO implements Comparable<SplitMsgPacketDTO> {

	private static final String SPLIT_MSG_PACKET = "SPLITMSGPACKET";

	private String uuid;

	private int size;

	private int order;

	private String body;

	@Override
	public String toString() {
		return SPLIT_MSG_PACKET + JSONObject.toJSONString(this);
	}

	@Override
	public int compareTo(SplitMsgPacketDTO o) {
		return this.order - o.order;
	}

	public static RawMessageDTO merger(List<SplitMsgPacketDTO> cachedPackedDtoList) {

		Collections.sort(cachedPackedDtoList);

		List<String> list = Lists.newArrayList();

		int exceptedOrder = 0;

		for (SplitMsgPacketDTO dto : cachedPackedDtoList) {

			if (dto.getOrder() == exceptedOrder) {
				list.add(Base64Util.decrypt(dto.getBody()));
				exceptedOrder++;
			} else {
				return RawMessageDTO.EMPTYRAWMESSAGE;
			}

		}

		return RawMessageDTO.create(Joiner.on("").skipNulls().join(list));
	}

	public static List<String> generateMsgPacket(String msg) {
		List<String> result = Lists.newArrayList();

		List<String> msgPartList = Splitter.fixedLength(1500).splitToList(msg);

		if (msgPartList.size() == 1) {
			return msgPartList;
		}

		String uuid = MinaUtils.generateUUID();

		int size = msgPartList.size();

		for (int i = 0; i < size; i++) {
			String body = msgPartList.get(i);
			result.add(new SplitMsgPacketDTO(uuid, size, i, Base64Util.encrypt(body)).toString());
		}

		return result;
	}

}
